package com.totoro.rabbitmq.producer;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ生产者配置
 * 主要配置RabbitMQ的连接，以及RabbitMQ的操作模板类。（客户端在一个项目中，共用一个连接和模板）
 * Created by Administrator on 2017/9/14.
 */
@Configuration
public class ProductConfig {
    @Value("${spring.rabbitmq.addresses}")
    private String address ;
    @Value("${spring.rabbitmq.port}")
    private int port ;
    @Value("${spring.rabbitmq.username}")
    private String user ;
    @Value("${spring.rabbitmq.password}")
    private String password ;
    @Value("${spring.rabbitmq.virtual-host}")
    private String virtualHost ;
    @Value("${spring.rabbitmq.publisher-confirms}")
    private boolean publisherConfirms ;

    /**
     * 配置RabbitMQ连接
     * @return
     */
    @Bean
    public ConnectionFactory connectionFactory(){
        CachingConnectionFactory cachingconnectionfFactory = new CachingConnectionFactory() ;

        cachingconnectionfFactory.setAddresses(this.address);
        cachingconnectionfFactory.setUsername(this.user);
        cachingconnectionfFactory.setPassword(this.password);
//        cachingconnectionfFactory.setVirtualHost(this.virtualHost); //虚拟主机。一个RabbitMQ可以虚拟成多个host，主要为了做权限隔离，不同该用户范文不同的virtualHost
        cachingconnectionfFactory.setPublisherConfirms(this.publisherConfirms); //如果需要进行消息回调，这里需要设置为true


        //更多对connection, channel, listener的配置
        return cachingconnectionfFactory ;
    }

    /**
     * 配置RabbitMQ的API操作类
     * @param connectionFactory
     * @return
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory) ;
        return rabbitTemplate ;
    }


}
